<template>
  <div class="role-manage-container">
    <!-- 顶部筛选条件 -->
    <div class="conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <!-- 租户名称 -->
          <a-tree-select
            allow-clear
            placeholder="请选择租户名称"
            :replaceFields="{
              children: 'child',
              title: 'tenantName',
              key: 'id',
              value: 'tenantCode',
            }"
            v-model="conditions.proName"
            :tree-data="conditions.proNameSource"
            @change="tenantChange"
          >
          </a-tree-select>

          <!-- 角色名称 -->
          <bjSelect
            :dataResource="conditions.roleNameSource"
            placeholder="请选择角色名称"
            v-model="conditions.roleName"
            allowClear
            :replaceFields="{ key: 'roleCode', label: 'roleName' }"
            @change="selectChange($event, 'roleName')"
            :loading="conditions.roleNameLoading"
          ></bjSelect>
          <!-- 状态 -->
          <bjSelect
            :dataResource="conditions.statusSource"
            placeholder="请选择状态"
            v-model="conditions.status"
            @change="selectChange($event, 'status')"
            allowClear
          ></bjSelect>
        </template>
        <template slot="operate">
          <a-button type="primary" @click="search()"> 查询 </a-button>
        </template>
      </ScreenConditions>
    </div>

    <!-- 主体区域 -->
    <div class="result-container">
      <div class="common-result-container-header" header="角色管理">
        <a-button type="primary" @click="addOperate(0)" v-if="showButton">
          新增
        </a-button>
      </div>
      <div class="result-body">
        <!-- table -->
        <div class="table-container">
          <vxe-table
            align="center"
            :data="table.source"
            show-overflow
            show-header-overflow
            show-footer-overflow
            show-footer
            :column-config="{ resizable: true }"
            class="scrollbarStyle"
            height="99%"
            :sort-config="{ trigger: 'cell' }"
            ref="xTable"
            :scroll-x="{ gt: 10 }"
            :scroll-y="{ gt: 100 }"
            row-id="id"
            :checkbox-config="{
              reserve: true,
            }"
          >
            <vxe-column
              :title="item.title"
              :field="item.key"
              :key="index"
              :min-width="item.width"
              show-overflow
              v-for="(item, index) in table.columns"
            >
              <template slot-scope="scope">
                <!-- 角色类型 -->
                <div v-if="item.key == 'roleType'">
                  {{ scope.row.roleType | filterRoleType }}
                </div>
                <!-- 状态 -->
                <div v-else-if="item.key == 'disabled'">
                  <span
                    :class="[
                      checkStatusClassName(scope.row.disabled),
                      'status-text',
                    ]"
                    >{{ filterRoleStatus(scope.row.disabled) }}</span
                  >
                </div>

                <div v-else>{{ scope.row[item.key] }}</div>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="280" fixed="right" align="left">
              <template #default="{ row }">
                <div class="text-button-group">
                  <a-button type="link" @click="goView(row)"> 查看 </a-button>
                  <a-button
                    type="link"
                    @click="addOperate(1, row)"
                    v-if="showButton"
                  >
                    编辑
                  </a-button>
                  <a-button
                    type="link"
                    @click="handleStopClick(row)"
                    v-if="showButton"
                  >
                    {{ row.disabled == 0 ? "停用" : "启用" }}
                  </a-button>

                  <a-popover
                    overlayClassName="table-more-btns-popover"
                    placement="bottom"
                    :getPopupContainer="() => $el"
                    v-if="showButton"
                  >
                    <template slot="content">
                      <div
                        class="popover-btn"
                        @click="openTenantModalVisible(row)"
                      >
                        租户菜单配置
                      </div>
                      <div
                        class="popover-btn"
                        @click="openUserConfigModal(row)"
                      >
                        用户配置
                      </div>
                      <div class="popover-btn" @click="openOrgConfigModal(row)">
                        组织配置
                      </div>
                      <div class="popover-btn" @click="openEquConfigModal(row)">
                        设备配置
                      </div>
                    </template>
                    <span class="table-more-btns">...</span>
                  </a-popover>
                </div>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <!-- 分页 -->
        <div class="pager-container">
          <vxe-pager
            background
            :current-page.sync="pager.page"
            :page-size.sync="pager.pageSize"
            :total="pager.total"
            :layouts="[
              'PrevPage',
              'JumpNumber',
              'NextPage',
              'Sizes',
              'FullJump',
            ]"
            @page-change="paginationChange"
          >
            <template #left>
              <div class="vxe-pager-left-tip-container">
                第<span>1</span>到<span
                  >{{ Math.ceil(pager.total / pager.pageSize) || 1 }}页 </span
                >共<span>{{ pager.total }}</span
                >条记录
              </div>
            </template>
          </vxe-pager>
        </div>
      </div>
    </div>
    <!-- 新增弹窗 -->
    <addModal
      :visible.sync="addVisible"
      :operateType="operateType"
      :params="params"
    ></addModal>
    <!-- 用户配置 -->
    <userConfigModal
      :visible.sync="userConfigModalVisible"
      :id="id"
    ></userConfigModal>
    <!-- 设备配置 -->
    <equipmentConfig
      :visible.sync="equimentModalVisible"
      :id="id"
    ></equipmentConfig>
  </div>
</template>

<script>
//【角色管理】列表
import bjSelect from "@/components/bj-select";
import addModal from "./components/addModal";
import userConfigModal from "./components/userConfigModal";
import equipmentConfig from "./components/equipmentConfig";
import { getLoginData } from "@/tools";
import { addAttributeByKey } from "@/utils";
import { getTenantList } from "@/api/user-center/organizationManage.js";
import { getPurView } from "@/api/user-center/userManage.js";
//
import {
  getRoleList,
  stopRole,
  startRole,
  getRoleName,
} from "@/api/user-center/roleManage.js";
export default {
  components: {
    bjSelect,
    addModal,
    userConfigModal,
    equipmentConfig,
  },
  data() {
    return {
      //顶部筛选条件
      conditions: {
        //租户名称
        proName: undefined,
        proNameSource: [],
        proNameLoading: false,
        //角色名称
        roleNameSource: [],
        roleName: undefined,
        roleNameLoading: false,
        //状态
        statusSource: [
          {
            key: 0,
            value: "正常",
          },
          {
            key: 1,
            value: "停用",
          },
        ],
        status: undefined,
      },
      //table
      table: {
        source: [{}],
        columns: [
          {
            title: "角色名称",
            dataIndex: "roleName",
            key: "roleName",
            width: "130px",
          },
          {
            title: "权限字符",
            dataIndex: "roleCode",
            key: "roleCode",
            width: "",
          },
          {
            title: "角色类型",
            dataIndex: "roleType",
            key: "roleType",
            width: "",
          },
          {
            title: "状态",
            dataIndex: "disabled",
            key: "disabled",
            width: "",
          },
          {
            title: "显示顺序",
            dataIndex: "sort",
            key: "sort",
            width: "",
          },
          {
            title: "创建时间",
            dataIndex: "createTime",
            key: "createTime",
            width: "110px",
          },
        ],
      },
      //分页
      pager: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      //新增弹窗
      addVisible: false,
      //用户配置弹窗
      userConfigModalVisible: false,
      //设备配置弹窗
      equimentModalVisible: false,
      //按钮权限
      showButton: false,
      operateType: 0,
      params: {},
      id: "",
    };
  },
  filters: {
    //校验角色类型名称 【1普通角色；2安全科角色】
    filterRoleType(val) {
      switch (val) {
        case "1":
          return "普通角色";

        case "2":
          return "安全科角色";

        default:
          return "--";
      }
    },
  },
  mounted() {
    this.getPurviewFlag();
    this.getTenantList();
    //初始化
    this.getListData({ pageSize: 10, page: 1 }).then((res) => {});
  },
  methods: {
    //新增、编辑
    addOperate(type = 0, row = {}) {
      this.params = row;
      this.operateType = type;
      this.addVisible = true;
    },
    //查询操作权限
    getPurviewFlag() {
      getPurView()
        .then((res) => {
          this.showButton = res?.data?.result || false;
        })
        .catch((_) => {
          this.showButton = false;
        });
    },

    //【查询条件】查询项目名称
    getTenantList() {
      return new Promise((resolve, reject) => {
        let { userId } = getLoginData();
        getTenantList({ userId })
          .then((res) => {
            let { data } = res;
            let tree = data?.result || [];
            this.conditions.proNameSource = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              tree,
              "child"
            );
            resolve();
          })
          .catch((_) => {
            this.conditions.proNameSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //选择租户
    tenantChange() {
      if (this.conditions.proName) this.getRoleNameList();
      else this.conditions.roleNameSource = [];
      this.conditions.roleName = undefined;
      this.search();
    },

    //【查询条件】角色名称
    getRoleNameList() {
      this.conditions.roleNameLoading = true;
      return new Promise((resolve, reject) => {
        let { proName } = this.conditions;
        getRoleName({ tenantCode: proName ? proName : "" })
          .then((res) => {
            let { data } = res;
            this.conditions.roleNameSource = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.conditions.roleNameSource = [];
            reject();
          })
          .finally((_) => {
            this.conditions.roleNameLoading = false;
          });
      });
    },

    //查询
    search() {
      this.pager.page = 1;
      this.pager.pageSize = 10;
      let { proName, roleName = {}, status = {} } = this.conditions;
      this.getListData({
        tenantCode: proName ? proName : "",
        roleCode: roleName?.key,
        status: status?.key,
        page: 1,
        pageSize: 10,
      });
    },

    //查询列表数据
    getListData(params = {}) {
      let {
        tenantCode = "",
        roleCode = "",
        status = "",
        page = 1,
        pageSize = 10,
      } = params;
      return new Promise((resolve, reject) => {
        getRoleList({
          tenantCode,
          roleCode,
          status,
          page,
          pageSize,
        })
          .then((res) => {
            let { data } = res;
            this.pager.total = data?.result?.total || 0;
            (data?.result?.rows || []).forEach((item) => {
              item.statusName = this.filterRoleStatus(item.disabled);
            });

            this.table.source = data?.result?.rows;
            resolve(data?.result || {});
          })
          .catch((_) => {
            this.pager.total = 0;
            this.table.source = [];
            resolve({});
          })
          .finally((_) => {});
      });
    },

    //搜索条件切换
    selectChange(ev, key) {
      this.$set(this.conditions, key, ev);
      this.pager.page = 1;
      this.pager.pageSize = 10;
      let { proName, roleName = {}, status = {} } = this.conditions;
      this.getListData({
        tenantCode: proName ? proName : "",
        roleCode: roleName?.key,
        status: status?.key,
        page: 1,
        pageSize: 10,
      });
    },

    //停用
    handleStopClick(row) {
      let that = this;
      let { id, disabled } = row;
      const h = this.$createElement;
      this.$confirm({
        title: `您确定${disabled == 0 ? "停用" : "启用"}所选角色吗?`,
        content: "",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        confirmLoading: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FB5A5A",
          }),
        onOk() {
          return new Promise((resolve, reject) => {
            (disabled == 0 ? stopRole : startRole)({ id })
              .then((res) => {
                that.$message.success("操作成功！");
                that.refreshData();
              })
              .finally((_) => {
                resolve();
              });
          });
        },
        onCancel() {},
      });
    },

    //操作后刷新列表
    refreshData() {
      let { proName, roleName = {}, status = {} } = this.conditions;
      let { page, pageSize } = this.pager;
      this.getListData({
        tenantCode: proName ? proName : "",
        roleCode: roleName?.key,
        status: status?.key,
        page,
        pageSize,
      });
    },

    //查看
    goView(row) {
      this.$router.push({
        path: `/nebula/user-app/roleManage/details`,
        query: {
          id: row.id,
        },
      });
    },

    //租户菜单配置
    openTenantModalVisible(row) {
      let { id } = row;
      this.$router.push({
        path: `/nebula/user-app/roleManage/menuConfig?id=${id}`,
      });
    },

    //用户配置
    openUserConfigModal(row) {
      let { id } = row;
      this.id = id;
      this.userConfigModalVisible = true;
    },

    //组织配置
    openOrgConfigModal(row) {
      let { id } = row;
      this.$router.push({
        path: `/nebula/user-app/roleManage/orgConfig?id=${id}`,
      });
    },

    //设备配置
    openEquConfigModal(row) {
      let { id } = row;
      this.id = id;
      this.equimentModalVisible = true;
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      let { proName, roleName = {}, status = {} } = this.conditions;
      this.getListData({
        tenantCode: proName ? proName : "",
        roleCode: roleName?.key,
        status: status?.key,
        page: currentPage,
        pageSize: pageSize,
      });
    },

    //校验状态名称
    filterRoleStatus(val) {
      switch (val) {
        case 0:
          return "正常";

        case 1:
          return "停用";

        default:
          return "--";
      }
    },

    //检验状态类名
    checkStatusClassName(status = 0) {
      switch (status) {
        case 0:
          return "";

        case 1:
          return "error";

        default:
          return "default";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.role-manage-container {
  height: 100%;
  .flex();
  flex-direction: column;
  box-sizing: border-box;
  padding: 0 0 10px 10px;
  /deep/.ant-popover {
    &.table-more-btns-popover {
      .ant-popover-inner-content {
        padding: 10px 0;
        .popover-btn {
          height: 30px;
          padding: 0 20px;
          .flex();
          justify-content: center;
          align-items: center;
          cursor: pointer;
          margin-bottom: 10px;
          color: #525a5d;
          &:last-child {
            margin: 0;
          }
          &:hover {
            background: #e9ecf3;
            color: var(--primary-color);
          }
        }
      }
    }
  }
  .conditions-container {
    flex-shrink: 0;
  }
  .result-container {
    .flex();
    flex-direction: column;
    flex: 1;
    .common-result-container-header {
      flex-shrink: 0;
    }
    .result-body {
      flex: 1;
      .flex();
      flex-direction: column;
      .table-container {
        flex: 1;
        .table-more-btns {
          color: var(--primary-color);
          margin-top: -20px;
          transform: translateY(-3px);
          margin-left: 20px;
          display: inline-block;
          cursor: pointer;
        }
        .status-text {
          background: #4bc964;
          border-radius: 4px;
          color: #fff;
          padding: 4px 15px;
          &.error {
            background: #ff3f4a;
          }

          &.default {
            background: #e9ecf3;
          }
        }
      }
      .pager-container {
        flex-shrink: 0;
      }
    }
  }
}
</style>
